using System.Collections.Generic;
using System.Text;

namespace Dorm.QueryObject
{
    public class Delete
    {
        protected string EntityName { get; set; }
        protected List<FilterExpression> Filters { get; set; }
        protected string WhereClause { get; set; }

        public Delete From(string entityName)
        {
            EntityName = entityName;
            return this;
        }

        public Delete Filter(string propertyName, FilterOptions comparison, object propertyValue)
        {
            if (Filters == null) Filters = new List<FilterExpression>();
            var filter = new FilterExpression
            {
                PropertyName = propertyName,
                Comparison = comparison,
                CompareValue = propertyValue
            };
            Filters.Add(filter);
            return this;
        }

        public Delete Where(string whereClause)
        {
            WhereClause = whereClause;
            return this;
        }

        public override string ToString()
        {
            var expression = new StringBuilder();

            expression.AppendLine("DELETE FROM " + EntityName);
            
            if (Filters != null)
            {
                expression.AppendLine("WHERE");
                expression.Append("      ");

                expression.AppendLine(Filters[0].ToString());

                if (Filters.Count > 1)
                {
                    for (int f = 1; f < Filters.Count; f++)
                    {
                        var concatenator = Filters[f].Concatenate ?? "AND";
                        expression.Append("  " + concatenator + " ");

                        expression.AppendLine(Filters[f].ToString());
                    }
                }
            }
            else if (WhereClause != null)
            {
                expression.AppendLine("WHERE");
                expression.AppendLine(WhereClause);
            }

            return expression.ToString();
        }
    }
}
